package client

import (
	"context"
	"google.golang.org/grpc"
	work "short-video-media/common/proto"
)

type Handler func(ctx context.Context, in work.WorkClient) (interface{}, error)

func WorkClient(ctx context.Context, handler Handler) (interface{}, error) {
	dial, err := grpc.Dial("127.0.0.1:8082", grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := work.NewWorkClient(dial)
	res, err := handler(ctx, client)
	if err != nil {
		return nil, err
	}
	return res, nil
}

func AddWork(ctx context.Context, i *work.AddWorkReq) (*work.AddWorkResp, error) {
	client, err := WorkClient(ctx, func(ctx context.Context, in work.WorkClient) (interface{}, error) {
		addWork, err := in.AddWork(ctx, i)
		if err != nil {
			return nil, err
		}
		return addWork, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*work.AddWorkResp), nil
}
func UpdateWork(ctx context.Context, i *work.UpdateWorkReq) (*work.UpdateWorkResp, error) {
	client, err := WorkClient(ctx, func(ctx context.Context, in work.WorkClient) (interface{}, error) {
		updateWork, err := in.UpdateWork(ctx, i)
		if err != nil {
			return nil, err
		}
		return updateWork, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*work.UpdateWorkResp), nil
}
func FindWork(ctx context.Context, i *work.FindWorkReq) (*work.FindWorkResp, error) {
	client, err := WorkClient(ctx, func(ctx context.Context, in work.WorkClient) (interface{}, error) {
		findWork, err := in.FindWork(ctx, i)
		if err != nil {
			return nil, err
		}
		return findWork, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*work.FindWorkResp), nil
}
